import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

//class Solution {
//    public List<List<Integer>> threeSum(int[] nums) {
//        Arrays.sort(nums);
//        int n = nums.length;
//        List<List<Integer>> ret = new ArrayList<>();
//        for (int i = 0; i < n; i++) {
//            if (i > 0 && nums[i] == nums[i - 1]) {
//                continue;
//            }
//            int left = i + 1, right = n - 1;
//            while (left < right) {
//                if (nums[left] + nums[right] + nums[i] < 0) {
//                    left++;
//                } else if (nums[left] + nums[right] + nums[i] > 0) {
//                    right--;
//                } else {
//                    //nums[left] + nums[right] + nums[i] == 0
//                    ret.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left++], nums[right--])));
//                    // left++; right--;
//                    //去重left、right
//                    while (left < right && nums[left] == nums[left - 1]) left++;
//                    while (left < right && nums[right] == nums[right + 1]) right--;
//                }
//            }
//        }
//        return ret;
//    }
//}

/**
 * 15. 三数之和
 * https://leetcode.cn/problems/3sum/description/?envType=study-plan-v2&envId=top-100-liked
 */
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        //1、排序
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> ret = new ArrayList<>();
        for(int i = 0; i < n; i++) {
            if(nums[i] > 0) break;
            //去重i
            if(i > 0 && nums[i] == nums[i - 1]) continue;

            int left = i + 1, right = n - 1, target = -nums[i];
            while(left < right) {
                if(nums[left] + nums[right] > target) {
                    right--;
                } else if(nums[left] + nums[right] < target) {
                    left++;
                } else {
                    ret.add(new ArrayList<>(Arrays.asList(nums[i], nums[left++], nums[right--])));
                    //去重 left、right
                    while(left < right && nums[left] == nums[left - 1]) left++;
                    while(left < right && nums[right] == nums[right + 1]) right--;
                }
            }
        }
        return ret;
    }
}